package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;

import com.qdlc.p2p.common.constant.RedStatus;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.RedEnvelopeAttachedService;
import com.qdlc.p2p.biz.service.RedEnvelopeService;
import com.qdlc.p2p.biz.service.UserVipLevelService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.exception.RedEnvelopeException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.NumberUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.RedEnvelope;
import com.qdlc.p2p.dal.dto.RedEnvelopeAttached;
import com.qdlc.p2p.dal.model.RedEnvelopeModel;

/**
 * 红包方案管理 Action
 *
 * @author ylx
 * @version 2.0
 * @date 2015年5月13日 下午5:40:22
 */
public class ManageRedEnvelopeAction extends BaseAction<RedEnvelopeModel> implements ModelDriven<RedEnvelopeModel> {

    @Resource
    private RedEnvelopeService redEnvelopeService;
    @Resource
    private RedEnvelopeAttachedService redEnvelopeAttachedService;
    @Resource
    private UserVipLevelService userVipLevelService;

    private RedEnvelopeModel model = new RedEnvelopeModel();

    public RedEnvelopeModel getModel() {
        return model;
    }

    private Map<String, Object> data = new HashMap<String, Object>();

    /**
     * 红包方案 页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeManager")
    public String redEnvelopeManager() throws Exception {

        return "redEnvelopeManager";
    }

    /**
     * 红包方案 列表
     *
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeList")
    public void redEnvelopeList() throws Exception {
        PageDataList<RedEnvelopeModel> pageDataList = redEnvelopeService.list(model);
        int total = pageDataList.getPage().getTotal();
        data.put("total", total);
        data.put("rows", pageDataList.getList());
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 红包方案详情 页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeDetailPage")
    public String redEnvelopeDetailPage() throws Exception {
        // 获取红包方案
        RedEnvelope redEnvelope = redEnvelopeService.getRedEnvelopeById(model.getId());
        if (null == redEnvelope)
            throw new RedEnvelopeException(MessageUtil.getMessage("MF100001014"));

        RedEnvelopeModel redEnvelopeModel = RedEnvelopeModel.instance(redEnvelope);
        request.setAttribute("redEnvelope", redEnvelopeModel);

        // 获取红包方案附属信息
        List<RedEnvelopeAttached> list = redEnvelopeAttachedService.list(model.getId());
        request.setAttribute("attachedList", list);
        return "redEnvelopeDetailPage";
    }

    /**
     * 红包方案修改 页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeEditPage")
    public String redEnvelopeEditPage() throws Exception {
        // 获取红包方案
        RedEnvelope redEnvelope = redEnvelopeService.getRedEnvelopeById(model.getId());
        if (null == redEnvelope)
            throw new RedEnvelopeException(MessageUtil.getMessage("MF100001014"));

        RedEnvelopeModel redEnvelopeModel = RedEnvelopeModel.instance(redEnvelope);
        request.setAttribute("redEnvelope", redEnvelopeModel);

        // 获取红包方案附属信息
        List<RedEnvelopeAttached> list = redEnvelopeAttachedService.list(model.getId());
        request.setAttribute("attachedList", list);
        return "redEnvelopeEditPage";
    }

    /**
     * 红包方案修改
     *
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    @Action("/modules/additional/redEnvelope/redEnvelopeEdit")
    public void redEnvelopeEdit() throws Exception {
        //检测红包方案常规值
        model.checkAddModel();
        //红包规则更新，同时更新vip等级配置中的红包奖励金额
        userVipLevelService.update(model.getAmount(), model.getId(), model.getPayType());
        //如果发放方式为区间金额或者区间比例则需要保存红包附属信息
        List<RedEnvelopeAttached> list = new ArrayList<RedEnvelopeAttached>();
        if (model.getPayType() == model.RED_ENVELOPE_PAY_INTERVAL_AMOUNT
                || model.getPayType() == model.RED_ENVELOPE_PAY_INTERVAL_RATE) {
            list = this.getRedEnvelopeAttachedList();

            //如果未填写红包附属信息则提示先填写红包附属信息
            if (list.size() == 0) {
                printResult(MessageUtil.getMessage("MF100001015"), false);
                return;
            }
        }

        //保存红包方案
        redEnvelopeService.update(model, list);

        printResult(MessageUtil.getMessage("MS100001004"), true);
    }

    /**
     * 红包方案添加 页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeAddPage")
    public String redEnvelopeAddPage() throws Exception {

        return "redEnvelopeAddPage";
    }

    /**
     * 红包方案添加
     *
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    @Action("/modules/additional/redEnvelope/redEnvelopeAdd")
    public void redEnvelopeAdd() throws Exception {
        //检测红包方案常规值
        model.checkAddModel();

        //如果发放方式为区间金额或者区间比例则需要保存红包附属信息
        List<RedEnvelopeAttached> list = new ArrayList<RedEnvelopeAttached>();
        if (model.getPayType() == model.RED_ENVELOPE_PAY_INTERVAL_AMOUNT
                || model.getPayType() == model.RED_ENVELOPE_PAY_INTERVAL_RATE) {
            list = this.getRedEnvelopeAttachedList();

            //如果未填写红包附属信息则提示先填写红包附属信息
            if (list.size() == 0) {
                printResult(MessageUtil.getMessage("MF100001015"), false);
                return;
            }
        }

        //保存红包方案
        redEnvelopeService.save(model, list);

        printResult(MessageUtil.getMessage("I10001"), true);
    }

    /**
     * 红包方案删除
     *
     * @throws Exception
     */
    @Action("/modules/additional/redEnvelope/redEnvelopeDelete")
    public void redEnvelopeDelete() throws Exception {
        redEnvelopeService.delete(model.getId());
        printResult(MessageUtil.getMessage("I10003"), true);
    }

    /**
     * 红包附属内容填充
     *
     * @return
     */
    @SuppressWarnings("static-access")
    private List<RedEnvelopeAttached> getRedEnvelopeAttachedList() {
        int payType = model.getPayType();
        List<RedEnvelopeAttached> list = new ArrayList<RedEnvelopeAttached>();
        String[] minArray = request.getParameterValues("startAmount");// 下限
        String[] maxArray = request.getParameterValues("endAmount");// 上限
        String[] moneyArray = request.getParameterValues("payAmount");// 金额
        String[] rateArray = request.getParameterValues("payRate");// 比率
        int size = minArray.length;
        for (int i = 0; i < size; i++) {
            if (payType == model.RED_ENVELOPE_PAY_INTERVAL_AMOUNT) {
                if (StringUtil.isBlank(minArray[i]) || StringUtil.isBlank(maxArray[i]) || StringUtil.isBlank(moneyArray[i])) {//判断是否有空值
                    continue;
                }
                RedEnvelopeAttached attached = new RedEnvelopeAttached(
                        model.RED_ENVELOPE_PAY_INTERVAL_AMOUNT,
                        NumberUtil.getDouble(minArray[i]),
                        NumberUtil.getDouble(maxArray[i]),
                        NumberUtil.getDouble(moneyArray[i]), 0);
                list.add(attached);
            }

            if (payType == model.RED_ENVELOPE_PAY_INTERVAL_RATE) {
                if (StringUtil.isBlank(minArray[i]) || StringUtil.isBlank(maxArray[i]) || StringUtil.isBlank(rateArray[i])) {//判断是否有空值
                    continue;
                }
                RedEnvelopeAttached attached = new RedEnvelopeAttached(
                        model.RED_ENVELOPE_PAY_INTERVAL_AMOUNT,
                        NumberUtil.getDouble(minArray[i]),
                        NumberUtil.getDouble(maxArray[i]),
                        0, NumberUtil.getDouble(rateArray[i]));
                list.add(attached);
            }
        }
        return list;
    }

    /**
     * 启用
     *
     * @throws IOException
     */
    @Action(value = "/modules/additional/redEnvelope/redEnvelopeEnable")
    public void redEnvelopeEnable() throws IOException {
        int result = redEnvelopeService.changeStatus(new long[]{model.getId()}, RedStatus.FORBIDDEN, RedStatus.USE);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("被禁用的红包才能被启用!", false);
        }
    }

    /**
     * 禁用
     *
     * @throws IOException
     */
    @Action(value = "/modules/additional/redEnvelope/redEnvelopeDisable")
    public void redEnvelopeDisable() throws IOException {
        int result = redEnvelopeService.changeStatus(new long[]{model.getId()}, RedStatus.USE, RedStatus.FORBIDDEN);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("正常的红包才能被禁用!", false);
        }
    }
}
